package cn.agiledata.security.db.service;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jxl.write.WritableWorkbook;

import org.apache.commons.beanutils.BeanUtils;

import cn.agiledata.security.db.bean.AutoEnctSetBean;
import cn.agiledata.security.db.bean.EnctListBean;
import cn.agiledata.security.db.dao.EnctListPage;
import cn.agiledata.security.db.form.EnctSelectForm;
import cn.agiledata.security.db.util.TitleUtil;

import cn.agiledata.bank.common.bean.JxlBean;
import cn.agiledata.bank.common.dao.HibernateDaoUtil;
import cn.agiledata.bank.common.service.IJxlService;
import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.DateUtil;
import cn.agiledata.bank.common.util.IOUtil;
import cn.agiledata.bank.common.util.PageBean;
import cn.agiledata.bank.common.util.StringUtil;
import cn.agiledata.bank.hibernateBean.Account;
import cn.agiledata.bank.hibernateBean.AccountBalance;
import cn.agiledata.bank.hibernateBean.Transaction;

public class EnctListServiceImpl implements IEnctListService,Constant{
	private IAvoidJuggleService avoidJuggleService;
	private IJxlService jxlService;
	private AutoEnctSetBean autoEnctSetBean;
	private HibernateDaoUtil util;
	
	
	public void setAutoEnctSetBean(AutoEnctSetBean autoEnctSetBean) {
		this.autoEnctSetBean = autoEnctSetBean;
	}
	public void setJxlService(IJxlService jxlService) {
		this.jxlService = jxlService;
	}
	public IAvoidJuggleService getAvoidJuggleService() {
		return avoidJuggleService;
	}
	public void setAvoidJuggleService(IAvoidJuggleService avoidJuggleService) {
		this.avoidJuggleService = avoidJuggleService;
	}

	public HibernateDaoUtil getUtil() {
		return util;
	}
	public void setUtil(HibernateDaoUtil util) {
		this.util = util;
	}
	/**
	 * 得到分页的角色列表
	 * @param roleBean
	 * @return
	 */
	public PageBean getEnctPagingList(EnctSelectForm form) {
		if(!StringUtil.isStrEmpty(form.getDbName())) {
			form.setNeedList(true);	//需要查询列表
			form.setNeedTotal(true); //需要查询全部条
			EnctListPage listPage = 
				new EnctListPage(form);
			PageBean pb = listPage.getAccountListPageBean();
			return pb;			
		} else {
			return null;
		}

	}
	
	public void autoAccountEnct() {
		autoEnct(ACCOUNT_DB);
	}
	public void autoTransactionEnct() {
		autoEnct(TRANSACTION_DB);
	}
	public void autoAccountBalanceEnct() {
		autoEnct(ACCOUNT_BALANCE_DB);
	}
	/**
	 * 自动检测
	 *
	 */
	public void autoEnct(String dbName) {
		EnctSelectForm form = new EnctSelectForm();
		String resultType = "";
		form.setDbName(dbName);
		if(dbName.equals(ACCOUNT_DB))	{
			resultType = autoEnctSetBean.getAutoEnctSetProps().getProperty(ACCOUNT_RESULT_TYPE);
		} 
		if(dbName.equals(ACCOUNT_BALANCE_DB))	{
			resultType = autoEnctSetBean.getAutoEnctSetProps().getProperty(ACCOUNT_BALANCE_RESULT_TYPE);
		}
		if(dbName.equals(TRANSACTION_DB))	{
			resultType = autoEnctSetBean.getAutoEnctSetProps().getProperty(TRANSACTION_RESULT_TYPE);
		}
		String[] resultTypes = resultType.split(",");
		
		
		form.setPageSize(ENCTLISTPAGESIZE.toString());
		
		
		if(resultTypes != null) {
			for(int i=0;i<resultTypes.length;i++) {
				form.setResultType(resultTypes[i].split(":")[0]);
				form.setResultTypeName(resultTypes[i].split(":")[1]);
				form.setStartPage("1");
				
				try{
					PageBean pb = getEnctList(form);
					JxlBean bean = renderXlsBean(pb,form,i,resultTypes.length);
					jxlService.writeXls(bean);
					
				}catch(Exception e){
					
				}				
			}
			
		}

	}
	public PageBean getEnctList(EnctSelectForm form) {
		PageBean pb = null;
		if("".equals(form.getResultType()) || ENCRCODEEMPTY_ERROR_CODE.equals(form.getResultType())) {
			pb = getEnctPagingList(form);
		} else {
			pb = getEnctErrorPagingList(form);
		}
		return pb;
	}
	/**
	 * 
	 * @param pb
	 * @return
	 */
	public JxlBean renderXlsBean(PageBean pb,EnctSelectForm form,int sheet,int totalSheet) {
		JxlBean bean = new JxlBean();
		String strFilename = "";
		if(form.getDbName().equals(ACCOUNT_DB)) {
			strFilename = autoEnctSetBean.getAutoEnctSetProps().getProperty(ACCOUNT_FILE_NAME);
		}
		if(form.getDbName().equals(ACCOUNT_BALANCE_DB)) {
			strFilename = autoEnctSetBean.getAutoEnctSetProps().getProperty(ACCOUNT_BALANCE_FILE_NAME);
		}
		if(form.getDbName().equals(TRANSACTION_DB)) {
			strFilename = autoEnctSetBean.getAutoEnctSetProps().getProperty(TRANSACTION_FILE_NAME);
		}
		
		bean.setFileName(strFilename);
		
		bean.setSheet(sheet);
		
		bean.setTotalSheet(totalSheet);
		
		bean.setSheetName(form.getResultTypeName());
		
		bean.setTitle(form.getDbName()+"表--"+DateUtil.date2String(new Date()));
		
		bean.setTableHead(TitleUtil.getDbTitle(form.getDbName()));
		
		bean.setTableContext(getContext(pb.getData(),form.getDbName()));
		
		return bean;
	}
	public List getContext(List data,String dbName) {
		List list = new ArrayList();
		if(data != null) {
			for(int i=0;i<data.size();i++) {
				List smallList = new ArrayList();
				EnctListBean bean = (EnctListBean)data.get(i);
				if(dbName.equals(ACCOUNT_DB)) {
					smallList.add(bean.getAccount_seq());
					smallList.add(bean.getAccount_name());
					smallList.add(bean.getAccount_email());
					smallList.add(bean.getAccount_mobile());
					smallList.add(bean.getResult_set()[1]);
				}
				if(dbName.equals(ACCOUNT_BALANCE_DB)) {
					smallList.add(bean.getAccountBalance_seq());
					smallList.add(bean.getAccountBalance_subAccountName());
					smallList.add(bean.getAccountBalance_name());
					smallList.add(bean.getAccountBalance_balance());
					smallList.add(bean.getAccountBalance_lockAmount());
					smallList.add(bean.getResult_set()[1]);					
				}
				if(dbName.equals(TRANSACTION_DB)) {
					smallList.add(bean.getTransaction_seq());
					smallList.add(bean.getTransaction_transId());
					smallList.add(bean.getTransaction_actionType());
					smallList.add(bean.getTransaction_creditName());
					smallList.add(bean.getTransaction_debitName());
					smallList.add(bean.getTransaction_amount());
					smallList.add(bean.getResult_set()[1]);					
				}

				list.add(smallList);
			}
		}
		return list;
	}
	/**
	 * 得到分页的错误列表
	 * @return
	 */
	public PageBean getEnctErrorPagingList(EnctSelectForm form) {
		if(!StringUtil.isStrEmpty(form.getDbName())) {
			int count = getObjectCount(form);
			form.setNeedTotalCount(count);
			List list = getObjectList(form);
			return renderErrorPagingList(list);
		} else {
			return null;
		}		
	}
	/**
	 * 得到总共条数
	 * @param form
	 * @return
	 */
	public int getObjectCount(EnctSelectForm form) {
		form.setNeedList(false);	//不需要查询列表
		form.setNeedTotal(true); //需要查询全部条			
		EnctListPage listPage = 
			new EnctListPage(form);			
		PageBean pb = listPage.getAccountListPageBean();
		return pb.getTotalCount();
	}
	/**
	 * 得到列表
	 * @param form
	 * @return
	 */
	public List getObjectList(EnctSelectForm form) {
		List rntList = new ArrayList();
		form.setStartPage("1");
		form.setNeedList(true);	//不需要查询列表
		form.setNeedTotal(false); //需要查询全部条
		int count = form.getNeedTotalCount();
		form.setNeedTotalCount(count);
		int time = (int)Math.ceil(count/ENCTLISTPAGESIZE.floatValue());
		
		for(int i=0;i<time;i++) {
			form.setStartPage(String.valueOf(i+1));
			EnctListPage listPage = 
				new EnctListPage(form);	
			PageBean pb = listPage.getAccountListPageBean();
			getEncrErrorList(pb.getData(),rntList,form);
			pb = null;
			listPage = null;
		}
		return rntList;
	}
	/**
	 * 构造出错的页面列表
	 * @param list
	 * @return
	 */
	public PageBean renderErrorPagingList(List list) {
		PageBean pb = new PageBean(list.size(),1,list.size());
		pb.setData(list);
		return pb;
	}
	/**
	 * 得到校验错误值
	 * @param object
	 * @return
	 */
	public String[] getEncrResult(Object object) {
		String encrCode = "";
		try {
			encrCode = BeanUtils.getProperty(object, ENCRYPTCODE);
		} 
		catch(Exception e) {
			return	new String[]{FIELD_ERROR_CODE,FIELD_ERROR}; 
		}
		if(StringUtil.isStrEmpty(encrCode)) {
			return new String[]{ENCRCODEEMPTY_ERROR_CODE,ENCRCODEEMPTY_ERROR}; //返回检验码为空
		}
		String nowCode =  (String)avoidJuggleService.parseEncrCode(object);
		if(!nowCode.equals(encrCode)) {
			return new String[]{ENCRCODEERROR_CODE,ENCRCODEERROR};	//数据被篡改
		} else {
			return new String[]{ENCRCODECORRECT_CODE,ENCRCODECORRECT};	//数据正确
		}
	}
	/**
	 * 数据不正确则记录进List中
	 * @param list
	 * @return
	 */
	public List getEncrErrorList(List list,List rntList,EnctSelectForm form) {
		String resultType = form.getResultType();
		if(list == null) {
			return null;
		} else {
			for(int i=0;i<list.size();i++) {
				Object object = (Object)list.get(i);
				EnctListBean bean = (EnctListBean)object;
				if(resultType.equals(bean.getResult_set()[0])) {	//数据不正确则记录进List中
					rntList.add(object);
				}
			}
			return rntList;
		}
	}
	/**
	 * 重新校验
	 * @param form
	 * @return
	 */
	public void reEncr(EnctSelectForm form) {
		String dbName = form.getDbName();
		String ids = form.getHiddenId();
		String[] idArray = ids.split(",");
		if(!StringUtil.isStrEmpty(dbName)) {
			List list = new ArrayList();
			for(int i=0;i<idArray.length;i++)	{
				Object object = null;
				if("Account".equals(dbName)) {
					object = (Account)util.getObjectById(Account.class, new Long(idArray[i]));
				}
				if("AccountBalance".equals(dbName)) {
					object = util.getObjectById(AccountBalance.class, new Long(idArray[i]));
				}
				if("Transaction".equals(dbName)) {
					object = util.getObjectById(Transaction.class, new Long(idArray[i]));
				}
				String encrCode = (String)avoidJuggleService.parseEncrCode(object);
				try {
					BeanUtils.setProperty(object, ENCRYPTCODE, encrCode);
				} 	catch(Exception e) {
				
				}
				list.add(object);
			}
			util.saveOrUpdateList(list);
		}
	}
}
